package com.cetccloud.ap.proxy.channel.cossDomain.s30.handler.send;

import com.cetccloud.ap.proxy.channel.Channel;
import com.cetccloud.ap.proxy.channel.cossDomain.s30.handler.recv.RecvChannelHandler;
import com.thunisoft.exchange.gateway.protocol.channel.GatewayChannelMessageType;
import com.thunisoft.exchange.gateway.protocol.channel.GatewayResponseMessage;
import com.thunisoft.exchange.gateway.protocol.entity.GatewayStatus;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName ResponseHandler
 * @Description TODO
 * @Author superz
 * @Date 2021/4/23 16:26
 * @Version 1.0
 **/
@Slf4j
@Component
public class ResponseHandler implements RecvChannelHandler<GatewayResponseMessage> {

    @Autowired
    private Channel crossDomainChannel;

    private static Map<String, String> codeMessageMap = new HashMap<>();

    static {
        codeMessageMap.put("302", "跨域传输时，接受端接收消息失败");
        codeMessageMap.put("402", "接收域推送消息至应用系统失败");
        codeMessageMap.put("500", "域之间或应用系统间无互通权限, 拒绝交换");
        codeMessageMap.put("501", "传输过程中对消息或文件进行哈希校验失败");
        codeMessageMap.put("502", "传输过程中文件或消息丢失");
    }

    @Override
    public GatewayChannelMessageType type() {
        return GatewayChannelMessageType.response;
    }

    @Override
    public void handle(GatewayResponseMessage channelMessage) {
        List<GatewayStatus> statusList = channelMessage.getData().getData();
        if (CollectionUtils.isNotEmpty(statusList)) {
            for (GatewayStatus status : statusList) {
                log.error("跨域交互失败, status: " + status.getStatus());
                String msgID = status.getMsgID();
                String errorMessage = codeMessageMap.getOrDefault(String.valueOf(status.getStatus()), "code: " + status.getStatus());
                crossDomainChannel.sendError(msgID, errorMessage);
            }
        }
    }

}
